package seismosurfer.domain;

import seismosurfer.data.DataTransferObject;
import seismosurfer.data.constants.ParameterNames;
import seismosurfer.util.Assert;
import seismosurfer.util.Notification;
import seismosurfer.util.Util;

/**
 * The layer supertype that implements common operations
 * needed by its subclasses.
 *
 */
public class DomainObject implements ParameterNames {

    public static final String MESSAGE = "message";

    protected DataTransferObject data = null;
    
    /** A reference to a Notification object, put here for convenience */
    protected Notification error = null;
    
    /**
     * Creates a domain object and initializes its data
     * with the given DataTransferObject object.
     * 
     * @param data the DataTransferObject object that contains 
     *             the data
     */ 
    public DomainObject(DataTransferObject data) {
        Assert.notNull(data, "DataTransferObject should not be set to null.");
        this.data = data;
        error = data.getNotification();
    }
    
    /**
     * Creates a domain object.
     *
     */
    public DomainObject() {
        error = new Notification();
    }
    
    /**
     * Provides access to the Notification object, that
     * is used for error handling.
     * 
     * @return the Notification object
     */
    protected Notification getNotification() {
        return error;
    }
    
    /**
     * Records the given error message in the Notification object
     * if the value of the field is blank or null.
     * 
     * @param value the text that contains the value of a field
     * @param field the text that contains the name of a field
     * @param message the error message to be stored in the Notification object
     * @return true if there was an error, false otherwise
     */
    protected boolean failIfNullOrBlank(String value, String field,
            String message) {
        if (Util.isNullOrBlank(value)) {
            getNotification().put(field, message);
            return true;
        }
        return false;
    }
    
    /**
     * Records the given error message in the Notification object
     * if the condition is true.
     * 
     * @param condition a boolean expression
     * @param field  the name of the field that is associated with
     *        an error message
     * @param message the error message
     */
    protected void fail(boolean condition, String field, String message) {
        if (condition) {
            getNotification().put(field, message);
        }
    }

}
